package com.yuxinmuyu.sports_management.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yuxinmuyu.sports_management.bean.entiy.SysUsers;
import com.yuxinmuyu.sports_management.bean.request.UserLoginRequest;
import com.yuxinmuyu.sports_management.config.JWTConfig;
import com.yuxinmuyu.sports_management.exception.BusinessException;
import com.yuxinmuyu.sports_management.exception.R;
import com.yuxinmuyu.sports_management.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.yuxinmuyu.sports_management.service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author 张钦栩
 * @Email 1784746527@qq.com
 * @Create 2024-06-22
 * @Description
 */
@RestController
@RequestMapping("/*")
@Api(value = "登录验证",tags = "登录验证")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    UserService userService;
    @Resource
    JWTConfig jwtConfig;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @ApiOperation("登录验证")
    @PostMapping("/login")
    public R<?> login(@RequestBody @Validated UserLoginRequest request) {
        String redisVerifyCode = redisTemplate.opsForValue().get(String.format(RedisKey.LOGIN_CAPTCHA_KEY, request.getUuid()));
        if (StringUtils.isBlank(redisVerifyCode)) {
            throw new BusinessException("验证码已失效");
        }
        if (!Objects.equals(request.getCode(), redisVerifyCode)) {
            throw new BusinessException("验证码错误");
        }
        SysUsers user=userService.getByID(request.getUserID());
        if(Objects.isNull(user)){
            throw new BusinessException("该用户名不存在！");
        }
        if(Objects.equals(user.getUserPwd(), Md5Util.getMD5String(request.getPassword()))){
            //存入创建userInfo 存入redis中
            JSONObject userInfo = new JSONObject();
            userInfo.put("userID", request.getUserID());
            userInfo.put("userName",user.getUserName());
            userInfo.put("deptID",user.getDeptID());
            userInfo.put("avater",user.getAvater());
            //获取用户token
            String token = JWTUtils.getToken(user.getUserID(), jwtConfig.getExpireSeconds());
            //缓存用户信息
            redisTemplate.opsForValue().set(String.format(RedisKey.LOGIN_INFO_KEY, user.getUserID()), userInfo.toJSONString());
            //缓存用户token
            redisTemplate.opsForValue().set(String.format(RedisKey.LOGIN_TOKEN_KEY, user.getUserID()), token);
            return R.success(token);
        }else{
            throw new BusinessException("密码错误！");
        }
    }
    @ApiOperation(value = "获取验证码")
    @GetMapping("login/getVerify/{uuid}")
    public void getVerify(HttpServletResponse response,@PathVariable String uuid) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            //输出验证码图片方法
            String randcode = randomValidateCode.getRandString(response, 4, 40, 95, 25);
            redisTemplate.opsForValue().set(String.format(RedisKey.LOGIN_CAPTCHA_KEY, uuid), randcode, 60, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }
    @ApiOperation("获取登录人的信息")
    @PostMapping("getInfo")
    public R<SysUsers> getInfo(){
        SysUsers users=new SysUsers();
        users.setUserName(UserUtil.getUserName());
        users.setType(UserUtil.getType());
        users.setUserID(UserUtil.getUserId());
        users.setAvater(UserUtil.getAvater());
        return R.success(users);
    }
    @ApiOperation("退出")
    @PostMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String userId = JWTUtils.getUserId(token);
        redisTemplate.delete(String.format(RedisKey.LOGIN_TOKEN_KEY, userId));
        redisTemplate.delete(String.format(RedisKey.LOGIN_INFO_KEY, userId));
        return R.success();
    }
}
